package it.sarasini.selectablelist;

import it.sarasini.dmp.DebugLog;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class SelectableAdapter extends ArrayAdapter<StateListItem> {

	private int currentSelectedPosition = -1;

	
	public SelectableAdapter(Context context, int textViewResourceId) {
		
		super(context, textViewResourceId);
	}

	@SuppressWarnings("unchecked")
	public SelectableAdapter(Context context, int textViewResourceId, List objects) {
		
		super(context, textViewResourceId, objects);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		View v = super.getView(position, convertView, parent);
		StateListItem currItem = getItem(position);
		
		if(v == null)
			return null;
		
		if(currItem.isSelected()) 
			v.setBackgroundColor(Color.DKGRAY);
		else
			v.setBackgroundColor(Color.BLACK);
		
		return v;
	}
	
	public void selectUnselectItem(int position) {
		
		StateListItem item = getItem(position);
		
		if(item.isSelected())
			unSelect(position);
		else 
			select(position);
	}
	
	public void select(int position) {
		
		try {
		
			if(currentSelectedPosition == position)
				return;
			
			getItem(position).select();
			
			if(currentSelectedPosition != -1)
				getItem(currentSelectedPosition).unSelect();
			
			currentSelectedPosition = position;
		
		}catch(Exception e) { DebugLog.log("Impossibile selezionare"); }
		
		notifyDataSetChanged();
	}
	
	public void selectFirst() {
		
		select(0);
	}
	
	public void unSelect(int position) {
		
		try {
		
			getItem(position).unSelect();
		
			currentSelectedPosition = -1;
		
		}catch(Exception e) { DebugLog.log("Impossibile deselezionare"); }
		
		notifyDataSetChanged();
	}

}
